package org.edu.common.utils;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;

@Component
public class FileUpload {

	public static String filePath = "";

	@Value("${edu.path.upload}")
	public void setFilePath(String filePath) {
		FileUpload.filePath = filePath;
	}

	//   public static final String FILE_PATH = "webapps/wbn/car_image/";
    //文件上传  
    public static String uploadFile(MultipartFile file, HttpServletRequest request, String uri) throws IOException {
        String fileName = file.getOriginalFilename();  
        if("".equals(  fileName )){
        	return "";
        }
        String loadpath = request.getSession().
				getServletContext()
				.getRealPath("/")
				+ uri;
        String type  = fileName.substring(fileName.lastIndexOf("."));
        File tempFile = new File(loadpath, new Date().getTime() + type);  
        if (!tempFile.getParentFile().exists()) {  
            tempFile.getParentFile().mkdir();  
        }  
        if (!tempFile.exists()) {  
            tempFile.createNewFile();  
        }  
        file.transferTo(tempFile);  
        return tempFile.getName();  
    }  
    public static FilePo uploadFile1(MultipartFile file, HttpServletRequest request, String uri) throws IOException {
    	String base64 = null;
    	String fileName= null;
    	return uploadFile1(file,base64,fileName,request, uri);
    }
    public static FilePo uploadBASE64(String base64, String fileName, HttpServletRequest request, String uri) throws IOException {
    	MultipartFile file = null;
    	return uploadFile1(file,base64,fileName,request, uri);
    }
    //文件上传  
    private static FilePo uploadFile1(MultipartFile file, String base64, String fileName, HttpServletRequest request, String uri) throws IOException {
    	FilePo filePo = new FilePo();
    	
    	if (fileName==null) {
    		fileName = file.getOriginalFilename();  
        	if("".equals(  fileName )){
        		return null;
        	}
		}
    	
    /*	String loadpath = request.getSession().
    			getServletContext()
    			.getRealPath("/");*/
		///String path22 = request.getContextPath().replace("/","");
/*		if(StrUtil.isEmpty(path22)){
			loadpath=loadpath + uri+"/"+DateUtil.getNow(DateUtil.TYPE2);
		}else{
			if(!loadpath.contains(path22)){
				loadpath+=filePath+"/";
			}
			loadpath=loadpath.replace(path22, filePath)
					.replace("wtpwebapps", "webapps")
					+ uri+"/"+DateUtil.getNow(DateUtil.TYPE2);
		}*/

		String loadpath=filePath +"/"+ uri+"/"+DateUtil.getNow(DateUtil.TYPE2);

    	String type  = fileName.substring(fileName.lastIndexOf("."));
    	if (base64!=null) {
			type=".jpeg";
		}
    	String fileR= new Date().getTime() + type;
    	File tempFile = new File(loadpath, fileR);
    	filePo.setWebPath(loadpath+"/"+fileR);
    	if (!tempFile.getParentFile().exists()) {  
    		tempFile.getParentFile().mkdirs();  
    	}  
    	
    	if (base64==null) {
    		if (!tempFile.exists()) {  
        		tempFile.createNewFile();  
        	}
    		file.transferTo(tempFile);  
		}else{
			generateImage(base64, tempFile.getPath());
		}
    	
    	filePo.setRealPath(tempFile.getPath());
    	filePo.setName(tempFile.getName());
    	filePo.setUploadName(fileName);
    	filePo.setExt(type);
    	return filePo;  
    }  

    //图片转化成base64字符串  
    public static String GetImageStr() {
		//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        String imgFile = "D:\\111.jpg";//待处理的图片  
        InputStream in = null;  
        byte[] data = null;  
        //读取图片字节数组  
        try   
        {  
            in = new FileInputStream(imgFile);          
            data = new byte[in.available()];  
            in.read(data);  
            in.close();  
        }   
        catch (IOException e)   
        {  
            e.printStackTrace();  
        }  
        //对字节数组Base64编码  
        BASE64Encoder encoder = new BASE64Encoder();  
        return encoder.encode(data);//返回Base64编码过的字节数组字符串  
    }  
      

	// base64字符串转化成图片
	public static boolean generateImage(String imgStr,String path) { // 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return false;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(path);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static void main(String[] args) {
		String aaa1 = GetImageStr();
		System.out.println(aaa1);
		String base = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCADYAMgDASIAAhEBAxEB/8QAHAABAAIDAQEBAAAAAAAAAAAAAAUGAgMEBwEI/8QAQRAAAQMCBAMFBAYIBgMBAAAAAQACAwQRBRIhMQZBURMiYXGBFJGhsQcjMkJSwRUkYnKC0fDxFjM0ktLhQ1Nzwv/EABgBAQADAQAAAAAAAAAAAAAAAAABAgME/8QAIBEBAQACAwADAQEBAAAAAAAAAAECEQMhMRITQUJRYf/aAAwDAQACEQMRAD8A9iO5RDuUQEREBEVb4g43wrAXupy41NWB/kxkd3948vLdBZEXktb9LOKljo6eip43m+Vwu4geul1Cjj7iMz9u+vcR+AGzfcFG1vi9zX1eN030u4pTPAmgjqGj7QfoT5EDT4/z9A4W44wvihpjhd2FU0XdBIRf06ptGlkREUoEREBERAREQEREBERAREQEREA7lEO5RARFhLKyCF80rg2ONpc5x2AG5QVfjnis4BRNpaQ3rqlpyn/1t2zefIevSx8dnnLc0kkneNyddz5ndd+PYvLjOM1FdKTeV/daT9hn3W+gt81AYlJezQNNrqF9FDnnrxlva93G+wWVU9jJXuYCGEm2q20IMOHSy7doQwfMqNrZe9l6ImsXSh538it1DWT0VVHUU8roponZmPabEFcI1N1tabi6D9D8EcXQ8U4VmfaOtgAE8Y2PRw8D8PdezL83cM4/UcPYzDX07j3TaRl9Ht5g/wBePJfoigrqfE6GGtpJBJBM3MxwSVSx0oiKUCIiA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LOxEnzY0/MKNccugK+NIJtooyxn+JlqzYTi+JVVYxs9a6RhuC0ADl4AL1CN2aJruoBXkOBaYlD3banbyK9eiFomD9kLnymq1jNERVSIiICIiAdyiHcogIiICIiAtc4aYJA82aWkE9NFsWuo/wBNL+4fkg88xAMMji0315KBqnAki11N1LnOfIHW0dbQH81C1NsxIXdi56jJo4zu0i/iuN7hDJlzEDkd13T2IIK4Khoc2x1LdlNQ2tmzNOa2mt+S3U36/O2FotBEA6T9tx2HlooGWf2cXL+6TYgq0YDCIsLY+9zIS8nrfb4WUb2adcgyttsuOV2+i6pnjUAril33U0aHnXZGgdF8d5o02Kzq0TWAX/SMdzcDXZevt+wLdF5Nw2ztK8ADUkD3letAWFui58/W08fURFRIiIgIiIB3KIdyiAiIgIiIC01bg2klJ/Afkty1VP8ApZf3D8kHmtR3TLoG9/QDbYeAUROb7KTqy4mTMSTm1uCOQ66qJmOpAXdi5q4p1wTGwK75lHVB1OqUiJr3WYbFXqmjyUkYdYkNF/cqDXEucGAXLjYAL0FpHZAX2CjH1N8aJHaGwXFKfALrlO91wylubvXtfWytUR8JYBkfC4G9i4EC+vitbMhILQQLLESNOZ7JX5jrsdDfxWYHeJA3OgWNaLXwbFnxOHLreUH0C9PVC4Epf17PraGK9/E6fmr6sMvWk8fUXxFVL6i+Ig+oviIPp3KIiAiIgIiIC01Tc1JMDzY75IiDzfEmhji0AAdAoOYi+qIu7HxzX1wzEHmoupcblEUVMQ9QS6qia094vaBbrdehRkZPREUYfpk55t1wyOLSSGBxP7ViERWqI0EHNq23QZQF1UsXaTMFtBqURZVePUOC6XssNkqCCDM/S/Qf3KsaIue+thERQCIiAN0REH//2Q==";
		String path ="D:\\work2017\\apache-tomcat-7.0.55\\webapps\\fileupload\\uploadfile\\2018-08-28\\1535445834938.jpeg";
		System.out.println(path);
		generateImage(base, path);
	}
    
  
    public static File getFile(HttpServletRequest request, String fileName, String uri) {
    	   String loadpath = request.getSession().
   				getServletContext()
   				.getRealPath("/")
   				+ uri;
        return new File(loadpath, fileName);  
    }  
    public static String getBasePath(HttpServletRequest request, boolean fileupload) {
    	String ssss ="";
		if (fileupload) {
			ssss =  filePath;
		}
    	String loadpath = request.getSession().
    			getServletContext()
    			.getRealPath("/").replace(request.getContextPath().replace("/",""),ssss).replace("wtpwebapps", "webapps");
    	return loadpath;  
    }  
}  